package com.roncoo.permission.config;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 越川豪
 * @Date: 2021/3/29 11:09
 */
@Configuration
public class ShiroConfig {

    /**
     * 创建shiroFilter
     * 负责拦截所有请求
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //添加Shiro内置过滤器
        Map<String,String> Maps = new LinkedHashMap<String,String>();
        // 配置系统公共资源(放在受限资源上面), 后台登录页面不认证
        Maps.put("/blogin","anon");
        // 配置系统受限资源, 所有页面都认证
        Maps.put("/*","authc");
        //将我们设置的内容添加到 内置过滤器里面
        Map<String, Filter> m=new HashMap<>();
        // 登录 authc
        m.put("authc",new LoginFilter());
        //加入我们定义的过滤器
        shiroFilterFactoryBean.setFilters(m);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(Maps);
        return  shiroFilterFactoryBean;
    }

    /**
     * 创建安全管理器
     * @param adminRlam
     * @return
     */
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(AdminRlam adminRlam){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //给安全管理器设置realm
        securityManager.setRealm(adminRlam);
        return securityManager;
    }

    /**
     * 创建自定义realm
     * @return
     */
    @Bean
    public AdminRlam adminRlam(CredentialsMatcher credentialsMatcher){
        AdminRlam adminRlam = new AdminRlam();
        adminRlam.setCredentialsMatcher(credentialsMatcher);
        return adminRlam;
    }

    @Bean(value = "credentialsMatcher")
    public CredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher=new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");//md5
//        credentialsMatcher.setHashIterations(2);
        return credentialsMatcher;
    }
}
